//
// 总收入：  昨天卖出： 240 个  昨天收入：   自用： 60个 补号：30个
//
// 昨天
// QQ量：done!=0  产号量： done=1     产号成功率：存活： alive='活'  存活率：
//     今天
// QQ量：产号量：      产号成功率：存活：  存活率：
//
// ===========================
// 按手机统计（昨天）
//                  CC      EE  009 011    （RoDevice)
// QQ量：25
// 产号量：18
// 产号率： 80%
// 存活：   12
// 存活率：60%
// ==========================
// //按手机统计（今天）
// CC      EE  009 011    （RoDevice)
// QQ量：25
// 产号量：18
// 产号率： 80%
// 存活：   12
// 存活率：60%

const { getDayStr } = require('./common')
const { mapAttributes, mapArrayAttributes } = require('../utils')
const { TimeRange } = require('../util')
const getIncome = async () => {
  const day = getDayStr(Date.now() - 24 * 60 * 60 * 1000)
  const income = await new Parse.Query('RoIncome').equalTo('incomeDay', day).first()
  const allIncome = await new Parse.Query('RoIncome').limit(1000).find()
  const total = allIncome.reduce((prev, cur) => {
    return prev + (cur.get('price') || 0)
  }, 0)
  const count = {
    total,
    sale: 0,
    keep: 0,
    patch: 0,
    price: 0
  }
  if (income) {
    return [Object.assign(count, mapAttributes(income, ['sale', 'keep', 'patch', 'price']))]
  } else {
    return [count]
  }
}

const getRoTasksRate = (roTasks, title) => {
  const count = roTasks.reduce((prev, cur) => {
    const done = cur.get('done')
    if (done !== 0) {
      prev.used++
    }
    if (done === 1) {
      prev.done++
    }
    if (cur.get('alive') === '活') {
      prev.alive++
    }
    if (cur.get('alive')) {
      prev.checked++
    }
    return prev
  }, {
    title,
    used: 0,
    done: 0,
    alive: 0,
    checked: 0,
    successRate: 0,
    aliveRate: 0
  })
  count.successRate = count.used ? ((count.done / count.used) * 100).toFixed(2) + '%' : ''
  count.aliveRate = count.checked ? ((count.alive / count.checked) * 100).toFixed(2) + '%' : ''
  return count
}

const getRoTasks = async (startTime, endTime) => {
  return await new Parse.Query('RoTask')
    .greaterThanOrEqualTo('startTime', new Date(startTime))
    .lessThanOrEqualTo('startTime', new Date(endTime))
    .limit(10000000)
    .find()
}

const getDeviceRate = (deviceList, roTasks, title) => {
  return mapArrayAttributes(deviceList, ['name'], (result, device) => {
    return Object.assign(
      {},
      result,
      getRoTasksRate(roTasks.filter(task => task.get('device') && task.get('device').id === device.id), title)
    )
  })
}

Parse.Cloud.define('roCount', async (req, res) => {
  try {
    const timeRange = new TimeRange()
    const thisDay = timeRange.thisDay()
    const lastDay = timeRange.lastDay()
    const beforeYesterday = timeRange.recentRange(2, 1)
    const findThisDayTasks = getRoTasks(...thisDay)
    const findLastDayTasks = getRoTasks(...lastDay)
    const findBeforeYesterdayTasks = getRoTasks(...beforeYesterday)
    const findDeviceList = new Parse.Query('RoDevice').limit(10000).find()

    const thisDayTasks = await findThisDayTasks
    const lastDayTasks = await findLastDayTasks
    const beforeYesterdayTasks = await findBeforeYesterdayTasks
    const deviceList = await findDeviceList

    const result = {
      income: await getIncome(),
      thisDayRate: [getRoTasksRate(thisDayTasks, '今天')],
      lastDayRate: [getRoTasksRate(lastDayTasks, '昨天')],
      beforeYesterdayRate: [getRoTasksRate(beforeYesterdayTasks, '前天')],
      thisDayDeviceRate: getDeviceRate(deviceList, thisDayTasks, '今天'),
      lastDayDeviceRate: getDeviceRate(deviceList, lastDayTasks, '昨天'),
      beforeYesterdayDeviceRate: getDeviceRate(deviceList, beforeYesterdayTasks, '前天')
    }
    res.success(result)
  } catch (err) {
    res.error(err)
  }
})